﻿using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Text.RegularExpressions;
using MyTimeLine.Models;



public static class Funcoes
{
    public static myTimelineEntities Db
    {
        get { return new myTimelineEntities(); }
    }

    #region Json Functions

    /// <summary>
    /// JSON Serialization (by Maxwel)
    /// <param name="jsonObject">Objeto Json para virar String</param>
    /// </summary>
    public static string JsonSerializer<T>(T jsonObject)
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
        MemoryStream ms = new MemoryStream();
        ser.WriteObject(ms, jsonObject);
        string jsonString = Encoding.Default.GetString(ms.ToArray());
        ms.Close();

        //Replace Json Date String                                         
        const string pattern = @"\\/Date\((\d+)\+\d+\)\\/";
        MatchEvaluator matchEvaluator = ConvertJsonDateToDateString;
        Regex reg = new Regex(pattern);
        jsonString = reg.Replace(jsonString, matchEvaluator);

        return jsonString;
    }

    /// <summary>
    /// JSON Deserialization (by Maxwel)
    /// <param name="jsonString">String Json.Stringify</param>
    /// </summary>
    public static T JsonDeserialize<T>(string jsonString)
    {
        if (string.IsNullOrWhiteSpace(jsonString)) return default(T);

        //Converte "yyyy-MM-dd HH:mm:ss" String em "\/Date(1319266795390+0800)\/"
        const string pattern = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
        MatchEvaluator matchEvaluator = ConvertDateStringToJsonDate;

        Regex reg = new Regex(pattern);
        jsonString = reg.Replace(jsonString, matchEvaluator);
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
        MemoryStream ms = new MemoryStream(Encoding.Default.GetBytes(jsonString));
        T obj = (T)ser.ReadObject(ms);
        return obj;
    }

    /// <summary>
    /// Converte Serialization Time /Date(1319266795390+0800) em uma String
    /// </summary>
    private static string ConvertJsonDateToDateString(Match m)
    {
        DateTime dt = new DateTime(1970, 1, 1);
        dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value));
        dt = dt.ToLocalTime();
        //string result = dt.ToString("yyyy-MM-dd HH:mm:ss");
        string result = dt.ToString("dd/MM/yyyy HH:mm:ss");
        return result;
    }

    /// <summary>
    /// Converte Date String em Json Time
    /// </summary>
    private static string ConvertDateStringToJsonDate(Match m)
    {
        DateTime dt = DateTime.Parse(m.Groups[0].Value);
        dt = dt.ToUniversalTime();
        TimeSpan ts = dt - (new DateTime(1970, 1, 1));//DateTime.Parse("1970-01-01");
        string result = string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds);
        return result;
    }

    #endregion
}
